<?

class FormTaskListFilter extends CFormModel{
    
    public $filter = array();
    public $sorter = array(
        'order' => 'sort',
        'by' => 'asc',
        'critical' => 'before',
    );
    
    function __construct($scenario=''){
        parent::__construct($scenario);
        $this->filter['status'] = array(
            Task::model()->rstatuses[TaskModule::t('fields', 'Новая')],
            Task::model()->rstatuses[TaskModule::t('fields', 'В очереди')],
            Task::model()->rstatuses[TaskModule::t('fields', 'В процессе')],
            Task::model()->rstatuses[TaskModule::t('fields', 'Ожидает проверки')],
        );
        if(isset($_COOKIE['tasklist']['filter'])) $this->filter = unserialize($_COOKIE['tasklist']['filter']);
        if(isset($_COOKIE['tasklist']['sorter'])) $this->sorter = unserialize($_COOKIE['tasklist']['sorter']);
    }
    
    public function rules(){
        return array(
            array('filter, sorter', 'required'),
        );
    }
    
    public function attributeLabels(){
        return array(
            'filter'=>TaskModule::t('fields', 'Фильтр'),
            'sorter'=>TaskModule::t('fields', 'Сортировка'),
        );
    }
    
    function save(){
        setcookie('tasklist[filter]', serialize($this->filter), time()+3600*24*30);
        setcookie('tasklist[sorter]', serialize($this->sorter), time()+3600*24*30);
    }
    
    function generate($criteria){
        
        $this->save();
        
        $criteria->addInCondition('`t`.`status`', $this->filter['status']);
        
        $criteria->order = '`t`.`critical` desc, `t`.`'.$this->sorter['order'].'` '.$this->sorter['by'].'';
        
        return $criteria;
        
    }
    
}
